import axios from 'axios';
import { ElLoading } from 'element-plus';
import router from '@/router';
import Message from './Message';

const contentTypeForm = 'application/x-www-form-urlencoded;charset=UTF-8';
const contentTypeJson = 'application/json';
// arraybuffer / ARRAYBUFFER / json
// Blob 对象
const responseTypeJson = 'json';

let loading = null;
const instance = axios.create({
    baseURL: '/api',
    timeout: 50 * 1000,
});

// 请求前拦截器
instance.interceptors.request.use(
    (config) => {
        if (config.showLoading) {
            loading = ElLoading.service({
                lock: true,
                text: '加载中……',
                background: 'rgba(0,0,0,0)',
            });
        }
        return config;
    },
    (error) => {
        if (config.showLoading && loading) {
            loading.close();
        }
        Message.error("请求发送失败");
        return Promise.reject(error);
    }
);

// 请求后拦截器
instance.interceptors.response.use(
    (response) => {
        const { showLoading, errorCallback, showError = true, responseType } = response.config;

        // 关闭加载动画
        if (showLoading && loading) {
            loading.close();
        }

        // 处理响应数据
        let responseData = responseType === 'blob' ? response.data.data : response.data;

        // 请求成功（根据业务码判断）
        if (responseData.code === 200) {
            return Promise.resolve(responseData);
        }
        // 登录超时
        else if (responseData.code === 901) {
            router.push('/login');
            return Promise.reject({ showError: false, msg: "登录超时" });
        }
        // 其他错误
        else {
            if (errorCallback) {
                errorCallback(responseData.info);
            }
            return Promise.reject({ showError: showError, msg: responseData.info });
        }
    },
    (error) => {
        // 关闭加载动画
        if (error.config.showLoading && loading) {
            loading.close();
        }
        return Promise.reject({ showError: true, msg: "网络异常" });
    }
);

const request = (config) => {
    const {
        url,
        params,
        dataType,
        showLoading = true,
        responseType = responseTypeJson
    } = config;

    let contentType = contentTypeForm;
    let formData = new FormData(); // 创建表单对象

    // 处理请求参数
    for (let key in params) {
        formData.append(
            key,
            params[key] === undefined ? "" : params[key]
        );
    }

    // 设置内容类型
    if (dataType !== null && dataType === 'json') {
        contentType = contentTypeJson;
    }

    // 请求头配置
    let headers = {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest'
    };

    return instance.post(url, formData, {
        // 上传进度回调
        onUploadProgress: (event) => {
            if (config.uploadProgressCallback) {
                config.uploadProgressCallback(event);
            }
        },
        // 响应类型
        responseType: responseType,
        // 请求头
        headers: headers,
        // 加载状态控制
        showLoading: showLoading,
        // 错误回调
        errorCallback: config.errorCallback,
        // 是否显示错误
        showError: config.showError
    }).catch((error) => {
        if (error.showError) {
            Message.error(error.msg);
        }
        return null;
    });
};

export default request;

